from fastapi import FastAPI, HTTPException, Form,Depends,status
import mysql.connector
from mysql.connector import Error
from fastapi.middleware.cors import CORSMiddleware 
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt
import datetime

app = FastAPI()

# MySQL数据库配置
DB_CONFIG = {
    "host": "localhost",
    "user": "root",
    "password": "123456",
    "database": "xth",
    "port": 3306
}

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许的前端地址
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头
)
def get_db_connection():
    try:
        return mysql.connector.connect(**DB_CONFIG)
    except Error as e:
        print(f"数据库连接失败: {e}")
        return None

SECRET_KEY = "TESTMINI"
security = HTTPBearer()
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """
    验证JWT token并返回当前用户
    """
    token = credentials.credentials
    is_valid, result = decrypttoken(token)
    
    if not is_valid:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail={"status_code": 401, "msg": result},
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    return result['username']  # 返回解码后的用户名

def gettoken(username):
    payload = {
        'username': username,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)  # 过期时间
    }
    token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
    return token

def decrypttoken(token):
    try:
        decoded_payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        return(True,decoded_payload)
    except jwt.ExpiredSignatureError:
        return (False,"Token 过期")
    except jwt.InvalidTokenError:
        return(False,"无效的 Token")

@app.post("/register")
async def register(username: str = Form(...), password: str = Form(...)):
    conn = get_db_connection()
    if not conn:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = conn.cursor()
        cursor.execute("SELECT id FROM users WHERE username = %s", (username,))
        if cursor.fetchone():
            return {"status": False, "message": "用户名已存在"}
        
        cursor.execute(
            "INSERT INTO users (username, password) VALUES (%s, %s)",
            (username, password)
        )
        conn.commit()
        return {"status": True, "message": "注册成功！"}
    except Error as e:
        return {"status": False, "message": str(e)}
    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()

@app.post("/login")
async def login(username: str = Form(...), password: str = Form(...)):
    conn = get_db_connection()
    if not conn:
        raise HTTPException(status_code=500, detail="数据库连接失败")
    

    try:
        cursor = conn.cursor(dictionary=True)
        cursor.execute(
            "SELECT * FROM users WHERE username = %s AND password = %s",
            (username, password)
        )
        user = cursor.fetchone()
        print(user)
        if user:
           token = gettoken(username)
           return {
               "token": token,
               "token_type": "bearer"
           }
        else:
           return {"status": False, "message": "用户名或密码错误"}
    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()

@app.get("/")
async def health_check(username: str = Depends(get_current_user)):
    return {
        "message": f"你好, {username}! 这是一个受保护的路由",
        "status": True
}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)